package cn.net.shuxing.yifu.common.service;

import cn.net.shuxing.yifu.common.bean.HangBuy;
import cn.net.shuxing.yifu.common.bean.HangSale;
import cn.net.shuxing.yifu.common.bean.HangType;
import cn.net.shuxing.yifu.common.constant.DealScene;
import cn.net.shuxing.yifu.common.constant.DealState;
import cn.net.shuxing.yifu.common.constant.HangTypeConst;
import cn.net.shuxing.yifu.common.constant.UserType;
import cn.net.shuxing.yifu.common.util.JedisUtil;
import cn.net.shuxing.yifu.common.util.RedisKeyCreator;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.ScanParams;
import redis.clients.jedis.ScanResult;

import java.math.BigDecimal;
import java.time.LocalTime;
import java.util.List;

@Service
public class DealMatchService {

    @Autowired
    private JedisUtil jedisUtil;

    @Autowired
    private DealHistoryService dealHistoryService;

    @Autowired
    private HangSaleService hangSaleService;

    @Autowired
    private HangBuyService hangBuyService;

    @Autowired
    private UserCapitalService userCapitalService;

    public void match() {
        System.out.println("定时任务----->" + LocalTime.now().toString());
        /** 获取挂卖单集合 **/
        //Jedis //jedis = jedisUtil.getJedis();
        List<HangSale> hangSaleList = hangSaleService.getByState(DealState.DEALING);
        List<HangBuy> hangBuyList = hangBuyService.getByState(DealState.DEALING);

        for (HangSale hangSale : hangSaleList) {
            /** 获取挂卖单单价 **/
            BigDecimal hangSaleSinglePrice = hangSale.getSinglePrice();

            /** 如果挂卖单单价小于最新价,则系统回购 **/
            Integer coinTypeId = hangSale.getCoinTypeId();
            if (hangSaleSinglePrice.compareTo(new BigDecimal(jedisUtil.get(RedisKeyCreator.openPrice(coinTypeId)))) <= 0) {
                Integer hangSaleId = hangSale.getId();
                dealHistoryService.systemBuyBack(hangSaleId);
                continue;
            }

            for (HangBuy hangBuy : hangBuyList) {
                BigDecimal hangBuySinglePrice = hangBuy.getSinglePrice();
                boolean equals = hangBuy.getCoinTypeId().equals(hangSale.getCoinTypeId());
                if (hangBuySinglePrice.compareTo(hangSaleSinglePrice) == 0 && equals) {
                    /** 币种相同且价格相等就进行交易 **/
                    Integer hangBuyId = hangBuy.getId();
                    Integer hangSaleId = hangSale.getId();
                    dealHistoryService.deal(hangBuyId, hangSaleId);
                    break;
                }
            }
        }
    }
}
